<?php

class tvrage {

    private $months = array(
        1 => "jan",
        2 => "feb",
        3 => "mar",
        4 => "apr",
        5 => "may",
        6 => "jun",
        7 => "jul",
        8 => "aug",
        9 => "sep",
        10 => "oct",
        11 => "nov",
        12 => "dec",
    );
    private $shows = array("impact wrestling" => "tna_impact",
        "wwe smackdown" => "WWE_SmackDown",
        "craig ferguson" => "The_Late_Late_Show_with_Craig_Ferguson",
        "wwe friday night smackdown" => "WWE_SmackDown",
        "wwe monday night raw" => "WWE_Raw",
        "wwe nxt" => "WWE_NXT",
        "wwe raw" => "WWE_RAW",
        "wwe pay per view" => "WWE_Pay-Per-View",
        "wwe tough enough" => "WWE_Tough_Enough",
        "wwe saturday morning slam" => "shows/id-32554",
        "wwe superstars" => "shows/id-22359",
        "wwe main event" => "shows/id-32702",
        "daily show" => "The_Daily_Show",
        "the daily show" => "The_Daily_Show",
    );

    private function get_list($content) {
        $dom = new DOMDocument();
        $dom->loadHTML($content);
        foreach ($dom->getElementsByTagName('td') as $node) {
            $node_html = $dom->saveHTML($node);
            $node_strip = strip_tags($node_html);
            if (strstr($node_html, 'td width="40" align="center"><a href=')) {
                $eps_info = $node_strip;
                $eps_date = false;
            } else
            if (strstr($node_html, 'td width="80" align="center">'))
                $eps_date = strtolower($node_strip);
            if ($eps_date)
                $eps[$eps_date] = $eps_info;
        }
        return $eps;
    }

    public function airdate_to_episode($name, $date) {
        $ctx = stream_context_create(
                array(
                    'http' => array(
                        'timeout' => 3
                    )
                )
        );
        $nameshows=$name;
        foreach ($this->shows as $show => $rename) {
            if ($name == $show) {
                $nameshows = $rename;
                break;
            }
        }
        $tvrage_name = str_replace(" ", "_", $nameshows);

        $content = file_get_contents("http://www.tvrage.com/{$tvrage_name}/episode_list/all", null, $ctx);
        if (!$content)
            return false;
        $list = $this->get_list($content);
        $date = strtolower(str_replace(array(".", " "), "/", $date));
        $datee = explode("/", $date);
        $datef = (int) $datee[0];
        $month = $this->months[(int) $datee[1]];
        if ($datef > 1900 and $datef < 2100)
            $date = "{$datee[2]}/{$month}/{$datee[0]}";
        else
            $date = "{$datee[0]}/{$month}/{$datee[2]}";
        $ep = $list[$date];
        $epe = explode("x", $ep);
        return array($name, $epe[0], $epe[1]);
    }

}

?>
